<?php

namespace addons\groupon\listener\order;

use addons\groupon\exception\Exception;
use addons\groupon\library\traits\Groupon;
use addons\groupon\model\ActivityGoodsSkuPrice;
use addons\groupon\model\Goods;
use addons\groupon\model\GoodsSkuPrice;
use addons\groupon\model\User;
use addons\groupon\model\UserCoupons;
use addons\groupon\library\traits\StockSale;

/**
 * 订单失效
 */
class Invalid
{
    use StockSale;

    // 订单取消后行为
    public function GrouponOrderCancelAfter(&$params)
    {
        $order = $params['order'];

        $this->invalid($order, 'cancel');

        return $order;
    }


    // 订单关闭后行为
    public function GrouponOrderCloseAfter(&$params)
    {
        $order = $params['order'];

        $this->invalid($order, 'close');
    }



    // 订单取消或关闭返还
    private function invalid($order, $type) {
        // 如果有优惠券， 返还优惠券
        if ($order->coupons_id) {
            $coupon = UserCoupons::where('id', $order->coupons_id)->find();

            if ($coupon) {
                $coupon->usetime = null;
                $coupon->save();
            }
        }
        
        // 返还销量库存
        $this->realBackStockSale($order);

        return $order;

    }
}
